package com.lqzs.businessmanager.service

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.accessibilityservice.GestureDescription.StrokeDescription
import android.content.Context
import android.graphics.Path
import android.graphics.Rect
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityEvent.TYPE_VIEW_CLICKED
import android.view.accessibility.AccessibilityEvent.TYPE_VIEW_SCROLLED
import android.view.accessibility.AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
import android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.annotation.RequiresApi
import com.lqzs.businessmanager.BusinessManagerApplication
import com.lqzs.businessmanager.Config
import com.lqzs.businessmanager.bean.event.CallBackMinEvent
import com.lqzs.businessmanager.bean.event.HomeClickEvent
import com.lqzs.businessmanager.bean.event.ServiceEvent
import com.lqzs.businessmanager.utils.PreferencesUtil
import com.lqzs.businessmanager.utils.VID
import com.lqzs.businessmanager.utils.nodeOnClick
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


@Suppress("DEPRECATION")
class AccessibilitySampleService : AccessibilityService() {

    companion object{
            val TAG: String = javaClass.name
    }
    private var mService: AccessibilitySampleService? = null
    //美团外卖事件处理
    private val mViewModel = MeiTuanViewModel()
//    private val mNaposViewModel = NaposViewModel()

    private var mMerchantModel = MerchantModel()
//    private val mMTUserViewModel = MeiTuanUserViewModel()
    //当前活跃页面包名
    private var mActivityName = ""
    //当前活跃控件名称
    private var mWidgetName: String? = null

    private var measureWidth = 0
    private var measureHeight = 0
    //根节点
    private var rootNodeInfo : AccessibilityNodeInfo? = null

    private lateinit var mContext: Context


    private lateinit var mHandler: Handler
    private lateinit var mRunnable: Runnable

    override fun onServiceConnected() {
        super.onServiceConnected()
        Log.e("我的服务","服务connected")
        EventBus.getDefault().post(ServiceEvent())
        mService = this
        softKeyboardController.addOnShowModeChangedListener { controller, showMode ->
            controller.setShowMode(SHOW_MODE_HIDDEN)
        }
    }

    /**
     * 通过该方法执行点击操作、输入文本操作、滚动操作、获取文本操作
     */
    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        Log.e("我的服务","服务回调了一次")
        rootNodeInfo = event?.source
        if (event != null && event.className != null) {
            mWidgetName = event.className.toString()
            mWidgetName?.let {
                if (it.contains("com.sankuai")) {
                    mActivityName = it
                }
            }
        }


        val type = event!!.eventType

        when(type){
            TYPE_VIEW_CLICKED->{
                //用户点击了试图
                Log.d(TAG,"用户点击了试图")
            }
            TYPE_WINDOW_STATE_CHANGED->{
                //窗口状态发生了变化
                mMerchantModel.isScrollChange.set(0)
                Log.d(TAG,"窗口状态发生了变化")
            }
            TYPE_VIEW_SCROLLED->{
                //滚动视图发生了变化
                mMerchantModel.isScrollChange.set(0)
                Log.d(TAG,"滚动视图发生了变化")
                mViewModel.isScrollBottom =0
            }
            TYPE_VIEW_TEXT_CHANGED->{
                //文本视图发生了变化
                Log.d(TAG,"文本视图发生了变化")
            }
        }


        rootInActiveWindow?.let {
            val windowBounds = Rect()
            it.getBoundsInScreen(windowBounds)
            // 获取屏幕的宽度和高度
            if (windowBounds.right!=0){
                measureWidth = windowBounds.right
            }
            if (windowBounds.bottom!=0){
                measureHeight = windowBounds.bottom
            }
        }
        Log.e("我的服务","监听到的包名"+rootNodeInfo?.packageName.toString())
        rootNodeInfo?.let {
//            Log.d(TAG,"type:$type | mClassName:$mActivityName | mWidgetName:$mWidgetName")
            initTime(it)
            //遍历查询节点
            handler(event,it,type)
        }

    }

    //查找根节点
    private fun handler(event: AccessibilityEvent, rowNode: AccessibilityNodeInfo, type: Int) {

        when(rowNode.childCount){
            1->{
                rowNode.getChild(0)?.let {
                    handler(event, it, type)
                }
            }
            in 2..Int.MAX_VALUE->{
                CoroutineScope(Dispatchers.IO).launch {
                    val packageName = rowNode.packageName
                    when(packageName){
                        mContext.packageName ->{
                            //主App
                        }
                        Config.SYSTEM_SETTING->{
                            handlerSetting(rowNode)
                        }
                        Config.MIUI_PAGENAME->{
                            rootNodeInfo?.let {
                                if (it.className!=null){
                                    handlerMiui(it)
                                }
                            }
                        }
                        Config.SYSTEM_PAGENAME->{
                            handlerSystem(rowNode)
                        }
                        //美团外卖商家
                        Config.PACKAGE_NAME_MEITUAN_TAKEAWAY_BUSINESS ->{
                            mViewModel.handlerMeiTuan(rowNode)
                        }
                        //饿了么外卖商家
                        Config.PACKAGE_NAME_NAPOS ->{
/*                            //关闭声音弹窗
                            mNaposViewModel.voiceDialogDismiss(rowNode)
                            //关闭声音提示弹窗
                            mNaposViewModel.voiceTiXingDialogDismiss(rowNode)
                            val loadNodeInfo =
                                rowNode.findAccessibilityNodeInfosByText("加载中")
                            if (loadNodeInfo.isNotEmpty())
                                return@launch
                            //查询WebView相关节点
                            mNaposViewModel.handlerEle(rowNode)*/

                        }
                        //美团、大众点评到店
                        Config.PACKAGE_NAME_MERCHANT ->{
                            if (mMerchantModel.findText(rowNode,"门店选择")){
                                return@launch
                            }
                            mMerchantModel.handleEditText(this@AccessibilitySampleService,rowNode)
                            mMerchantModel.handleMerChantModel(this@AccessibilitySampleService,rowNode,event)
                        }
                        Config.PACKAGE_NAME_MEITUAN_HOTEL_BUSINESS ->{
                            //美团酒店商家
                            handlerHotel(rowNode)
                        }
                    }
                }
            }
        }
    }

    private fun handlerLog(rowNode: AccessibilityNodeInfo): Boolean {

        if (rowNode.childCount >0){
            for (i in 0 until rowNode.childCount){
                val  childNodeInfo = rowNode.getChild(i) ?: continue
                val className = childNodeInfo.className ?: continue
                Log.e(TAG," $className       ${childNodeInfo.viewIdResourceName}        ${childNodeInfo.text?.toString()?.trim()}")
                handlerLog(childNodeInfo)
            }
        }
        return false
    }

    /**
     * 定时任务开启
     */
    @Volatile
    var isClear = false
    @Volatile
    var isClickMineApp = false
    @Volatile
    var isTime = 0
    private fun initTime(rowNode: AccessibilityNodeInfo) {
        //开启定时任务
        val timeNodeInfo = rowNode.findAccessibilityNodeInfosByViewId(VID.tv_time)
        if (timeNodeInfo.isNotEmpty()){
            val time = timeNodeInfo[0].text?:return
            val currTime = time.toString().trim()
            if (currTime.contains(Config.time) ||currTime.contains(Config.time1)){
                if (isTime == 0){
                    systemRefresh()
                    isTime = 1
                }
            }else{
                isTime = 0
            }
        }

    }

    /**
     * 查找设置页面相关节点
     */
    private fun handlerSetting(rowNode: AccessibilityNodeInfo) {

    }

    /**
     * 查找小米系统相关节点
     */
    private suspend fun handlerMiui(rowNode: AccessibilityNodeInfo) {
        withContext(Dispatchers.Main){
            if (isClickMineApp){
                for (i in 0 until rowNode.childCount){
                    val  childNodeInfo = rowNode.getChild(i) ?: continue
                    val content = childNodeInfo.contentDescription?: continue
                    val className = childNodeInfo.className?: continue
                    if (className == FrameLayout::class.java.name
                        &&content.toString().trim().contains("BusinessManager")){
                        nodeOnClick(childNodeInfo)
                        childNodeInfo.recycle()
                        isClear = true
                        isClickMineApp = false
                        return@withContext
                    }else{
                        childNodeInfo.recycle()
                        handlerMiui(childNodeInfo)
                    }
                }
            }
        }

    }

    /**
     * 查找系统相关节点
     */
    fun handlerSystem(rowNode: AccessibilityNodeInfo){
        if (isClear){
            clickGaiLan(true)
            isClear = false
        }
    }

    /**
     * 美团酒店数据相关处理
     */
    private fun handlerHotel(rowNode: AccessibilityNodeInfo) {

    }

    fun systemRefresh(){
        PreferencesUtil.putBoolean(mContext,Config.NO_REPLAY,false)

        mHandler.postDelayed(mRunnable, 500)
        rootNodeInfo?.let {
            it.performAction(AccessibilityNodeInfo.ACTION_FOCUS)
            //路径点击
            val path = Path()
            path.moveTo((measureWidth/2).toFloat(), measureHeight-10f) // 假设的起始坐标
            path.lineTo((measureWidth/2).toFloat(), measureHeight-10f) // 点击操作，起点和终点相同
            val stroke = StrokeDescription(path, 0, 100)
            val gesture = GestureDescription.Builder().addStroke(stroke).build()
            // 执行手势
            dispatchGesture(gesture, object : GestureResultCallback() {
                override fun onCompleted(gestureDescription: GestureDescription) {
                    Log.e(TAG,"回到主界面")
                    isClickMineApp = true
                    mHandler.postDelayed({
                        clickGaiLan(false)
                    },1000)
                }

                override fun onCancelled(gestureDescription: GestureDescription) {
                    // 手势取消时调用
                }
            }, null) // 手势执行的 Handler，传 null 表示在主线程执行
        }

    }

    fun clickGaiLan(isClear:Boolean){
        val btGailan = rootNodeInfo?.findAccessibilityNodeInfosByViewId(VID.bt_gailan)
        if (!btGailan.isNullOrEmpty()){
            for (childNodeInfo in btGailan){
                val content = childNodeInfo.contentDescription?: continue
                val className = childNodeInfo.className?: continue
                val childContent = content.toString().trim()
                if (className == ImageView::class.java.name
                    &&childContent=="概览"){
                    nodeOnClick(childNodeInfo)
                    childNodeInfo.refresh()
                    if (isClear){
                        mHandler.postDelayed({
                            val clearNode = rootInActiveWindow?.findAccessibilityNodeInfosByViewId("com.miui.home:id/clearAnimView")
                            if (!clearNode.isNullOrEmpty()){
                                nodeOnClick(clearNode[0])
                                clearNode[0].recycle()
                                EventBus.getDefault().post(ServiceEvent())
                            }
                        },500)
                    }
                }
            }
        }else{
            mHandler.postDelayed({
                clickGaiLan(isClear)
            },500)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onHomeClick(event: CallBackMinEvent){
        systemRefresh()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onHomeClick(event: HomeClickEvent){
        Log.e("我的服务","eventbus的回调");
        if (event.measureWidth!=0){
            measureWidth = event.measureWidth
        }
        if (event.measureHeight!=0){
            measureHeight = event.measureHeight
        }

        mViewModel.replayStatus = Config.IS_REPLAY
        mMerchantModel.init(this)
        mViewModel.init(this)
//        mMTUserViewModel.init(this)
//        mNaposViewModel.init(this)
        if (event.type != 3 && event.type!=4){
            openShop(event.type)
        }
    }

    /**
     * 打开美团App后打开店铺页面
     */
    private fun openShop(type: Int) {
        when (type) {
            1 -> {
                Log.e(TAG, "打开美团外卖商家版的店铺")
                //路径点击
                val path = Path()
                //720 x 1600
                val pointX = (measureWidth / 2).toFloat()
                val pointY = (measureHeight - BusinessManagerApplication.getBottomNavigationBarHeight() - 40).toFloat()
                Log.d(TAG, "open shop $pointX  $pointY")
                path.moveTo(pointX, pointY) // 假设的起始坐标
                clickCoordinate(path, 10000L, object : GestureResultCallback() {
                    override fun onCompleted(gestureDescription: GestureDescription) {
                        openAppraise(type)
                        // 手势完成时调用
                        Log.e(TAG, "打开顾客评价页面结束")
                    }

                    override fun onCancelled(gestureDescription: GestureDescription) {
                        // 手势取消时调用
                        Log.e(TAG, "打开顾客评价页面失败")
                    }
                })
            }
        }

    }



    /**
     * 打开顾客评价页面
     * 224f,523f//中心
     * 196f,494f//左上
     * 248f,549f//右下
     * type 1美团外卖商家 2饿了么商家
     */
    private fun openAppraise(type: Int) {
        val path = Path()
        when(type){
            1->{
                path.moveTo(213.0f/720.0f*measureWidth, 484.0f/1600f*measureHeight) // 假设的起始坐标
                path.lineTo(213.0f/720.0f*measureWidth, 484.0f/1600f*measureHeight) // 点击操作，起点和终点相同
                Log.e(TAG,"店铺点击 ——》      ${213.0f/720.0f*measureWidth} ${484.0f/1600f*measureHeight}")
            }
            2->{
                path.moveTo(211.0f/720.0f*measureWidth, 389.0f/1600f*measureHeight) // 假设的起始坐标
                path.lineTo(211.0f/720.0f*measureWidth, 389.0f/1600f*measureHeight) // 点击操作，起点和终点相同
                Log.e(TAG,"店铺点击 ——》      ${211.0f/720.0f*measureWidth} ${389.0f/1600f*measureHeight}")
            }
        }
        clickCoordinate(path,3000L,object : GestureResultCallback() {
            override fun onCompleted(gestureDescription: GestureDescription) {
                // 手势完成时调用
                Log.e(TAG,"打开顾客评价页面结束")
            }

            override fun onCancelled(gestureDescription: GestureDescription) {
                // 手势取消时调用
                Log.e(TAG,"打开顾客评价页面失败")
            }
        })
    }


    /**
     * 点击坐标点位置
     */
    fun clickCoordinate(path: Path,time:Long,gestureResultCallback: GestureResultCallback){
        mHandler.postDelayed({
            rootNodeInfo?.let {
                val stroke = StrokeDescription(path, 0, 100)
                val gesture = GestureDescription.Builder().addStroke(stroke).build()
                // 执行手势
                dispatchGesture(gesture, gestureResultCallback, null) // 手势执行的 Handler，传 null 表示在主线程执行
            }
        },time)
    }

    override fun onInterrupt() {
        mService = this
    }

    override fun onDestroy() {
        super.onDestroy()
        mService = null
        EventBus.getDefault().unregister(this)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate() {
        super.onCreate()
        mContext = this

        EventBus.getDefault().register(this)
        mHandler = Handler(Looper.getMainLooper())
        mRunnable = Runnable {
            // 在这里执行你的任务
            // 例如，打开一个应用程序或执行某个操作
            performTask()
        }
    }


    private fun performTask() {
        // 使用 PackageManager 打开另一个 App
        val packageManager = packageManager
        val intent = packageManager.getLaunchIntentForPackage("com.lqzs.businessmanager.ui.main.activity.MainActivity")
        if (intent!= null) {
            startActivity(intent)
        } else {
            Log.e(TAG, "无法找到另一个 App 的启动意图")
        }
    }

}